package org.csu.linkgame.controller;

import com.jfoenix.controls.JFXButton;
import com.jfoenix.controls.JFXDialog;
import com.leewyatt.rxcontrols.controls.RXAvatar;
import com.leewyatt.rxcontrols.controls.RXFillButton;
import com.leewyatt.rxcontrols.controls.RXLineButton;
import com.leewyatt.rxcontrols.controls.RXTextField;
import com.leewyatt.rxcontrols.event.RXActionEvent;
import de.felixroske.jfxsupport.FXMLController;
import javafx.animation.FadeTransition;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.image.Image;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.StackPane;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javafx.stage.WindowEvent;
import javafx.util.Duration;
import org.csu.linkgame.domain.GameHistory;
import org.csu.linkgame.domain.GameLevel;
import org.csu.linkgame.domain.Log;
import org.csu.linkgame.domain.User;
import org.csu.linkgame.utils.AlertView;
import org.csu.linkgame.utils.MD5Utils;
import org.csu.linkgame.utils.ServiceUtil;
import org.pan.decorate.StageDecorate;

import java.io.IOException;
import java.net.URL;
import java.util.*;
import java.util.Timer;

@FXMLController
public class AdminViewController implements Initializable {

    @FXML
    private TableView<User> userInfoTable;
    @FXML
    private TableView<GameLevel> gameLevelTable;
    @FXML
    private TableView<GameHistory> gameHistoryTable;
    @FXML
    private TableView<Log> systemLogTable;
    @FXML
    private TableColumn<User, String> usernameCol;
    @FXML
    private TableColumn<User, String> passwordCol;
    @FXML
    private TableColumn<User, String> nicknameCol;
    @FXML
    private TableColumn<User, String> isAdminCol;
    @FXML
    private TableColumn<User, String> rankCol;
    @FXML
    private TableColumn<User, String> goalCol;
    @FXML
    private TableColumn<User, String> portCol;
    @FXML
    private TableColumn<User, String> friendCol;

    @FXML
    private TableColumn<GameLevel, String> levelCol;
    @FXML
    private TableColumn<GameLevel, String> unitSizeCol;
    @FXML
    private TableColumn<GameLevel, String> screenWidthCol;
    @FXML
    private TableColumn<GameLevel, String> screenLengthCol;
    @FXML
    private TableColumn<GameLevel, String> rowCountCol;
    @FXML
    private TableColumn<GameLevel, String> colCountCol;

    @FXML
    private TableColumn<GameHistory, Integer> gameHistoryIdCol;
    @FXML
    private TableColumn<GameHistory, String> winnerCol;
    @FXML
    private TableColumn<GameHistory, String> loserCol;
    @FXML
    private TableColumn<GameHistory, Date> endTimeCol;
    @FXML
    private TableColumn<GameHistory, String> gameLevelCol;

    @FXML
    private TableColumn<Log, Integer> logIdCol;
    @FXML
    private TableColumn<Log, Date> logTimeCol;
    @FXML
    private TableColumn<Log, String> logInfoCol;

    @FXML
    public JFXButton systemLogButton;
    @FXML
    public JFXButton gameHistoryButton;
    @FXML
    public JFXButton gameLevelButton;
    @FXML
    public JFXButton userInfoButton;

    @FXML
    private Tab userInfoTab;
    @FXML
    private Tab gameLevelTab;
    @FXML
    private Tab gameHistoryTab;
    @FXML
    private Tab systemLogTab;

    @FXML
    private RXTextField userInfoTextField;
    @FXML
    private RXTextField gameLevelTextField;
    @FXML
    private RXTextField gameHistoryTextField;
    @FXML
    private RXTextField systemLogTextField;

    @FXML
    private JFXDialog dialog;
    private StackPane dialogStackPane;

    @FXML
    private Label welcomeLabel;
    @FXML
    private TabPane tabPane;
    @FXML
    private AnchorPane anchorPane;
    @FXML
    private RXLineButton adminName;
    @FXML
    private RXAvatar avatar;
    @FXML
    private RXFillButton signOutButton;

    // 选中行
    private List<Integer> selectUserInfoCol = null;
    private List<Integer> selectGameLevelCol = null;
    private List<Integer> selectGameHistoryCol = null;
    private List<Integer> selectLogCol = null;

    private ObservableList<User> users;
    private ObservableList<GameLevel> gameLevels;
    private ObservableList<GameHistory> gameHistories;
    private ObservableList<Log> logs;

    private Collection<String> usernameList = new ArrayList<>();
    private Collection<Integer> gameLevelList = new ArrayList<>();
    private Collection<Integer> gameHistoryList = new ArrayList<>();
    private Collection<Integer> systemLogList = new ArrayList<>();

    private HashMap userInfoHashMap = new HashMap();
    private HashMap gameLevelHashMap = new HashMap();

    AlertView alertView;
    User user;
    String baseUrl = "http://orange-1312206514.cos.ap-guangzhou.myqcloud.com/images/";
    String adminUrl = baseUrl + "test.jpg";
//    Image image = new Image(adminUrl);
    Image image;
    public void setUser(User user) {
        this.user = user;
        adminUrl = baseUrl + user.getUsername() + ".jpg";
        adminName.setText(user.getUsername());

        image = new Image(adminUrl);
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        tabPane.getTabs().remove(userInfoTab);
        tabPane.getTabs().remove(gameLevelTab);
        tabPane.getTabs().remove(gameHistoryTab);
        tabPane.getTabs().remove(systemLogTab);

//
//        avatar.setImage(new Image(adminUrl));
//        Platform.runLater(() -> { avatar.setImage(new Image(adminUrl));});

        // 设置多选删除1
        userInfoTable.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
        gameLevelTable.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
        gameHistoryTable.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
        systemLogTable.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);

        userInfoTable.getSelectionModel().selectedItemProperty().addListener(// 选中某一行
            new ChangeListener<User>() {
                @Override
                public void changed(ObservableValue<? extends User> observableValue, User oldItem, User newItem) {
                    selectUserInfoCol = userInfoTable.getSelectionModel().getSelectedIndices();
                }
            }
        );

        gameLevelTable.getSelectionModel().selectedItemProperty().addListener(// 选中某一行
                new ChangeListener<GameLevel>() {
                    @Override
                    public void changed(ObservableValue<? extends GameLevel> observableValue, GameLevel oldItem, GameLevel newItem) {
                        selectGameLevelCol = gameLevelTable.getSelectionModel().getSelectedIndices();
                    }
                }
        );

        gameHistoryTable.getSelectionModel().selectedItemProperty().addListener(// 选中某一行
                new ChangeListener<GameHistory>() {
                    @Override
                    public void changed(ObservableValue<? extends GameHistory> observableValue, GameHistory oldItem, GameHistory newItem) {
                        selectGameHistoryCol = gameHistoryTable.getSelectionModel().getSelectedIndices();
                    }
                }
        );

        systemLogTable.getSelectionModel().selectedItemProperty().addListener(// 选中某一行
                new ChangeListener<Log>() {
                    @Override
                    public void changed(ObservableValue<? extends Log> observableValue, Log oldItem, Log newItem) {
                        selectLogCol = systemLogTable.getSelectionModel().getSelectedIndices();
                    }
                }
        );
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {

                image = new Image(adminUrl);
                FadeTransition ft = new FadeTransition(Duration.millis(2000), welcomeLabel);
                ft.setFromValue(1.0);
                ft.setToValue(0);
                ft.setCycleCount(0);
                ft.play();
                if (!image.isError()) {
                    avatar.setImage(image);
                }
            }
        };
        TimerTask timerTask1 = new TimerTask() {
            @Override
            public void run() {
                welcomeLabel.setVisible(false);
            }
        };
        Timer timer = new Timer();
        long delay = 1000;
        // 先执行动画淡出
        timer.schedule(timerTask, delay);
        // 再关闭Label
        timer.schedule(timerTask1, delay * 3);



        List<User> userList = ServiceUtil.serviceUtil.userService.getAllUserInfo();
        List<GameLevel> gameLevelList = ServiceUtil.serviceUtil.gameLevelService.getAllGameLevel();
        List<GameHistory> gameHistoryList = ServiceUtil.serviceUtil.gameHistoryService.getAllGameHistory();
        List<Log> logList = ServiceUtil.serviceUtil.logService.getAllLog();

        users = FXCollections.observableArrayList(userList);
        gameLevels = FXCollections.observableArrayList(gameLevelList);
        gameHistories = FXCollections.observableArrayList(gameHistoryList);
        logs = FXCollections.observableArrayList(logList);

        usernameCol.setCellValueFactory(new PropertyValueFactory<>("username"));
        passwordCol.setCellValueFactory(new PropertyValueFactory<>("password"));
        nicknameCol.setCellValueFactory(new PropertyValueFactory<>("nickname"));
        isAdminCol.setCellValueFactory(new PropertyValueFactory<>("isAdmin"));
        rankCol.setCellValueFactory(new PropertyValueFactory<>("userRank"));
        goalCol.setCellValueFactory(new PropertyValueFactory<>("userGoal"));
        portCol.setCellValueFactory(new PropertyValueFactory<>("userPort"));
        friendCol.setCellValueFactory(new PropertyValueFactory<>("userFriend"));

        levelCol.setCellValueFactory(new PropertyValueFactory<>("level"));
        unitSizeCol.setCellValueFactory(new PropertyValueFactory<>("unitSize"));
        screenWidthCol.setCellValueFactory(new PropertyValueFactory<>("sceneWidth"));
        screenLengthCol.setCellValueFactory(new PropertyValueFactory<>("sceneLength"));
        rowCountCol.setCellValueFactory(new PropertyValueFactory<>("rowCount"));
        colCountCol.setCellValueFactory(new PropertyValueFactory<>("colCount"));

        gameHistoryIdCol.setCellValueFactory(new PropertyValueFactory<>("gameHistoryId"));
        winnerCol.setCellValueFactory(new PropertyValueFactory<>("winner"));
        loserCol.setCellValueFactory(new PropertyValueFactory<>("loser"));
        endTimeCol.setCellValueFactory(new PropertyValueFactory<>("endTime"));
        gameLevelCol.setCellValueFactory(new PropertyValueFactory<>("gameLevel"));

        logIdCol.setCellValueFactory(new PropertyValueFactory<>("logId"));
        logInfoCol.setCellValueFactory(new PropertyValueFactory<>("logInfo"));
        logTimeCol.setCellValueFactory(new PropertyValueFactory<>("logTime"));

        userInfoTable.setEditable(false);
        gameLevelTable.setEditable(false);
        gameHistoryTable.setEditable(false);
        systemLogTable.setEditable(false);
    }

    public void openUserInfoTab(ActionEvent event) {
        if (!tabPane.getTabs().contains(userInfoTab)) {
            tabPane.getTabs().add(userInfoTab);
        }
        tabPane.getSelectionModel().select(userInfoTab);
        passwordCol.setPrefWidth(230);
        friendCol.setPrefWidth(490);
        insertUserInfoToTable();
    }

    public void openGameLevelTab(ActionEvent event) {
        if (!tabPane.getTabs().contains(gameLevelTab)) {
            tabPane.getTabs().add(gameLevelTab);
        }
        tabPane.getSelectionModel().select(gameLevelTab);
        levelCol.setPrefWidth(100);
        unitSizeCol.setPrefWidth(100);
        screenWidthCol.setPrefWidth(100);
        screenLengthCol.setPrefWidth(100);
        rowCountCol.setPrefWidth(100);
        colCountCol.setPrefWidth(100);
        insertGameLevelToTable();
    }

    public void openGameHistoryTab(ActionEvent event) {
        if (!tabPane.getTabs().contains(gameHistoryTab)) {
            tabPane.getTabs().add(gameHistoryTab);
        }
        tabPane.getSelectionModel().select(gameHistoryTab);
        winnerCol.setPrefWidth(100);
        loserCol.setPrefWidth(100);
        gameLevelCol.setPrefWidth(100);
        endTimeCol.setPrefWidth(180);
        insertGameHistoryToTable();
    }

    public void openSystemLogTab(ActionEvent event) {
        if (!tabPane.getTabs().contains(systemLogTab)) {
            tabPane.getTabs().add(systemLogTab);
        }
        tabPane.getSelectionModel().select(systemLogTab);
        logTimeCol.setPrefWidth(180);
        logInfoCol.setPrefWidth(990);
        insertLogToTable();
    }

    private void insertUserInfoToTable() {
        users = FXCollections.observableArrayList(ServiceUtil.serviceUtil.userService.getAllUserInfo());
        userInfoTable.setItems(users);
    }

    private void insertGameLevelToTable() {
        gameLevels = FXCollections.observableArrayList(ServiceUtil.serviceUtil.gameLevelService.getAllGameLevel());
        gameLevelTable.setItems(gameLevels);
    }

    private void insertGameHistoryToTable() {
        gameHistories = FXCollections.observableArrayList(ServiceUtil.serviceUtil.gameHistoryService.getAllGameHistory());
        gameHistoryTable.setItems(gameHistories);
    }

    private void insertLogToTable() {
        logs = FXCollections.observableArrayList(ServiceUtil.serviceUtil.logService.getAllLog());
        systemLogTable.setItems(logs);
    }

    public void removeUserInfoCol(ActionEvent event) {
        StringBuilder dialogContext = new StringBuilder();
        if (selectUserInfoCol != null && selectUserInfoCol.size() != 0) {
            for (int i = 0; i < selectUserInfoCol.size(); i++) {
                if (i != 0) {
                    dialogContext.append("、");
                }
                dialogContext.append(users.get(selectUserInfoCol.get(i)).getUsername());
            }
            alertView = new AlertView(Alert.AlertType.CONFIRMATION);
            alertView.setTitle("管理员请确认！");
            alertView.setHeaderText("你选择了" + dialogContext + "用户！");
            alertView.setContentText("是否删除？请选择！！！");
            Optional<ButtonType> result = alertView.showAndWait();
            if (result.get() == ButtonType.OK) {
                for (int i = selectUserInfoCol.size() - 1; i >= 0; i--) {
                    Integer integer = selectUserInfoCol.get(i);
                    System.out.println(integer);
                    usernameList.add(users.get(integer).getUsername());
                }
                if (ServiceUtil.serviceUtil.userService.deleteUserByUsernameList(usernameList) == selectUserInfoCol.size()) {
                    insertUserInfoToTable();
                    alertView.showAlert(Alert.AlertType.INFORMATION, "提示", "操作成功");
                } else {
                    alertView.showAlert(Alert.AlertType.ERROR, "数据库错误", "请检查数据库，稍后重试！");
                }
            }
        } else {
            alertView.showAlert(Alert.AlertType.WARNING, "警告！", "你没有选择任何数据项进行删除！！！");
        }
    }

    public void removeGameLevelCol(ActionEvent event) {
        StringBuilder dialogContext = new StringBuilder();
        if (selectGameLevelCol != null && selectGameLevelCol.size() != 0) {
            for (int i = 0; i < selectGameLevelCol.size(); i++) {
                if (i != 0) {
                    dialogContext.append("、");
                }
                dialogContext.append(gameLevels.get(selectGameLevelCol.get(i)).getLevel());
            }
            alertView = new AlertView(Alert.AlertType.CONFIRMATION);
            alertView.setTitle("管理员请确认！");
            alertView.setHeaderText("你选择了" + dialogContext + "级别的数据！");
            alertView.setContentText("是否删除？请选择！！！");
            Optional<ButtonType> result = alertView.showAndWait();
            if (result.get() == ButtonType.OK) {
                for (int i = selectGameLevelCol.size() - 1; i >= 0; i--) {
                    Integer integer = selectGameLevelCol.get(i);
                    System.out.println(integer);
                    gameLevelList.add(gameLevels.get(integer).getLevel());
                }
                if (ServiceUtil.serviceUtil.gameLevelService.deleteGameLevelByLevelList(gameLevelList) == selectGameLevelCol.size()) {
                    insertGameLevelToTable();
                    alertView.showAlert(Alert.AlertType.INFORMATION, "提示", "操作成功");
                } else {
                    alertView.showAlert(Alert.AlertType.ERROR, "数据库错误", "请检查数据库，稍后重试！");
                }
            }
        } else {
            alertView.showAlert(Alert.AlertType.WARNING, "警告！", "你没有选择任何数据项进行删除！！！");
        }
    }

    public void removeGameHistoryCol(ActionEvent event) {
        StringBuilder dialogContext = new StringBuilder();
        if (selectGameHistoryCol != null && selectGameHistoryCol.size() != 0) {
            for (int i = 0; i < selectGameHistoryCol.size(); i++) {
                if (i != 0) {
                    dialogContext.append("、");
                }
                dialogContext.append(gameHistories.get(selectGameHistoryCol.get(i)).getGameHistoryId());
            }
            alertView = new AlertView(Alert.AlertType.CONFIRMATION);
            alertView.setTitle("管理员请确认！");
            alertView.setHeaderText("你选择了" + dialogContext + "号数据！");
            alertView.setContentText("是否删除？请选择！！！");
            Optional<ButtonType> result = alertView.showAndWait();
            if (result.get() == ButtonType.OK) {
                for (int i = selectGameHistoryCol.size() - 1; i >= 0; i--) {
                    Integer integer = selectGameHistoryCol.get(i);
                    System.out.println(integer);
                    gameHistoryList.add(gameHistories.get(integer).getGameHistoryId());
                }
                if (ServiceUtil.serviceUtil.gameHistoryService.deleteGameHistoryByGameHistoryIdList(gameHistoryList) == selectGameHistoryCol.size()) {
                    insertGameHistoryToTable();
                    alertView.showAlert(Alert.AlertType.INFORMATION, "提示", "操作成功");
                } else {
                    alertView.showAlert(Alert.AlertType.ERROR, "数据库错误", "请检查数据库，稍后重试！");
                }
            }
        } else {
            alertView.showAlert(Alert.AlertType.WARNING, "警告！", "你没有选择任何数据项进行删除！！！");
        }
    }

    public void removeSystemLogCol(ActionEvent event) {
        StringBuilder dialogContext = new StringBuilder();
        if (selectLogCol != null && selectLogCol.size() != 0) {
            for (int i = 0; i < selectLogCol.size(); i++) {
                if (i != 0) {
                    dialogContext.append("、");
                }
                dialogContext.append(logs.get(selectLogCol.get(i)).getLogId());
            }
            alertView = new AlertView(Alert.AlertType.CONFIRMATION);
            alertView.setTitle("管理员请确认！");
            alertView.setHeaderText("你选择了" + dialogContext + "号日志！");
            alertView.setContentText("是否删除？请选择！！！");
            Optional<ButtonType> result = alertView.showAndWait();
            if (result.get() == ButtonType.OK) {
                for (int i = selectLogCol.size() - 1; i >= 0; i--) {
                    Integer integer = selectLogCol.get(i);
                    systemLogList.add(logs.get(integer).getLogId());
                }
                if (ServiceUtil.serviceUtil.logService.deleteLogByLogIdList(systemLogList) == selectLogCol.size()) {
                    insertLogToTable();
                    alertView.showAlert(Alert.AlertType.INFORMATION, "提示", "操作成功");
                } else {
                    alertView.showAlert(Alert.AlertType.ERROR, "数据库错误", "请检查数据库，稍后重试！");
                }
            }
        } else {
            alertView.showAlert(Alert.AlertType.WARNING, "警告！", "你没有选择任何数据项进行删除！！！");
        }
    }

    public void deleteText(RXActionEvent rxActionEvent) {
        userInfoTextField.setText("");
        gameLevelTextField.setText("");
        gameHistoryTextField.setText("");
        systemLogTextField.setText("");
    }

    public void searchUserInfo(ActionEvent event) {
        users = FXCollections.observableArrayList(ServiceUtil.serviceUtil.userService.getUsersByKeyword(userInfoTextField.getText()));
        userInfoTable.setItems(users);
    }

    public void searchGameLevel(ActionEvent event) {
        gameLevels = FXCollections.observableArrayList(ServiceUtil.serviceUtil.gameLevelService.getGameLevelsByKeyword(gameLevelTextField.getText()));
        gameLevelTable.setItems(gameLevels);
    }

    public void searchGameHistory(ActionEvent event) {
        gameHistories = FXCollections.observableArrayList(ServiceUtil.serviceUtil.gameHistoryService.getGameHistoriesByKeyword(gameHistoryTextField.getText()));
        gameHistoryTable.setItems(gameHistories);
    }

    public void searchSystemLog(ActionEvent event) {
        logs = FXCollections.observableArrayList(ServiceUtil.serviceUtil.logService.getLogsByKeyword(systemLogTextField.getText()));
        systemLogTable.setItems(logs);
    }

    public void insertUserInfoCol(ActionEvent event) throws IOException {
        alertView = new AlertView(Alert.AlertType.CONFIRMATION);
        alertView.setTitle("管理员请确认！");
        alertView.setHeaderText("即将弹出新用户信息填写窗口！");
        alertView.setContentText("是否打开？请选择！！！");
        Optional<ButtonType> result = alertView.showAndWait();
        if (result.get() == ButtonType.OK) {
            FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("../view/user.fxml"));
            Parent root = fxmlLoader.load();
            Stage stage = new Stage(StageStyle.DECORATED);
            stage.initModality(Modality.WINDOW_MODAL);
            stage.setScene(new Scene(root));
            StageDecorate.decorate(stage,root);
            stage.showAndWait();
            UserViewController userViewController = fxmlLoader.getController();
            userInfoHashMap = userViewController.getUserInfoHashMap();
            User user = new User();
            if (!userInfoHashMap.isEmpty()) {
                user.setUsername(userInfoHashMap.get("username").toString());
                String md5Pwd = MD5Utils.md5(userInfoHashMap.get("password").toString());
                user.setPassword(md5Pwd);
                user.setNickname(userInfoHashMap.get("nickname").toString());
                user.setIsAdmin(Integer.parseInt(userInfoHashMap.get("isAdmin").toString()));
                user.setUserRank(userInfoHashMap.get("userRank").toString());
                user.setUserGoal(userInfoHashMap.get("userGoal").toString());
                user.setUserPort(userInfoHashMap.get("userPort").toString());
                user.setUserFriend(userInfoHashMap.get("userFriend").toString());
                if (ServiceUtil.serviceUtil.userService.insertNewUserInfo(user) == 1) {
                    alertView = new AlertView(Alert.AlertType.INFORMATION);
                    alertView.setTitle("管理员请确认！");
                    alertView.setHeaderText("插入成功！");
                    alertView.setContentText("请查看插入后内容");
                    alertView.showAndWait();
                    insertUserInfoToTable();
                } else {
                    alertView = new AlertView(Alert.AlertType.ERROR);
                    alertView.setTitle("管理员请确认！");
                    alertView.setHeaderText("数据库错误！");
                    alertView.setContentText("请检查数据库！！！");
                    alertView.showAndWait();
                }
            }
        }
    }

    public void insertGameLevelCol(ActionEvent event) throws IOException {
        alertView = new AlertView(Alert.AlertType.CONFIRMATION);
        alertView.setTitle("管理员请确认！");
        alertView.setHeaderText("即将弹出新难度设置信息填写窗口！");
        alertView.setContentText("是否打开？请选择！！！");
        Optional<ButtonType> result = alertView.showAndWait();
        if (result.get() == ButtonType.OK) {
            FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("../view/level.fxml"));
            Parent root = fxmlLoader.load();
            Stage stage = new Stage(StageStyle.DECORATED);
            stage.initModality(Modality.WINDOW_MODAL);
            stage.setScene(new Scene(root));
            StageDecorate.decorate(stage,root);
            stage.showAndWait();
            LevelViewController levelViewController = fxmlLoader.getController();
            gameLevelHashMap = levelViewController.getNewGameLevelHashMap();
            GameLevel gameLevel = new GameLevel();
            if (!gameLevelHashMap.isEmpty()) {
                gameLevel.setLevel(Integer.parseInt(gameLevelHashMap.get("level").toString()));
                gameLevel.setUnitSize(Integer.parseInt(gameLevelHashMap.get("unitSize").toString()));
                gameLevel.setSceneWidth(Integer.parseInt(gameLevelHashMap.get("sceneWidth").toString()));
                gameLevel.setSceneLength(Integer.parseInt(gameLevelHashMap.get("sceneLength").toString()));
                gameLevel.setRowCount((Integer.parseInt(gameLevelHashMap.get("rowCount").toString())));
                gameLevel.setColCount(Integer.parseInt(gameLevelHashMap.get("colCount").toString()));
                if (ServiceUtil.serviceUtil.gameLevelService.insertNewGameLevel(gameLevel) == 1) {
                    alertView = new AlertView(Alert.AlertType.INFORMATION);
                    alertView.setTitle("管理员请确认！");
                    alertView.setHeaderText("插入成功！");
                    alertView.setContentText("请查看插入后内容");
                    alertView.showAndWait();
                    insertGameLevelToTable();
                } else {
                    alertView = new AlertView(Alert.AlertType.ERROR);
                    alertView.setTitle("管理员请确认！");
                    alertView.setHeaderText("数据库错误！");
                    alertView.setContentText("请检查数据库！！！");
                    alertView.showAndWait();
                }
            }
        }
    }
    public void backToLoginView(ActionEvent event) throws IOException{
        alertView = new AlertView(Alert.AlertType.CONFIRMATION);
        alertView.setTitle("管理员请确认！");
        alertView.setHeaderText("你将要退出登录！");
        alertView.setContentText("是否退出？请选择！！！");
        Optional<ButtonType> result = alertView.showAndWait();
        if (result.get() == ButtonType.OK) {
            Stage adminStage = (Stage) signOutButton.getScene().getWindow();
            adminStage.close();
            ServiceUtil.serviceUtil.logService.insertLog(user.getUsername() + "退出登录");
            FXMLLoader loader = new FXMLLoader(getClass().getResource("../view/login.fxml"));
            Parent root = loader.load();
            Stage stage = new Stage(StageStyle.DECORATED);
            stage.initModality(Modality.WINDOW_MODAL);
            stage.setScene(new Scene(root));
            StageDecorate.decorate(stage,root);
            stage.setTitle("超级连连看٩( 'ω' )و ");
            stage.getIcons().add(new Image("/org/csu/linkgame/images/icon.png"));
            stage.show();
        }
    }

    public void updateUserInfoCol(ActionEvent event) throws IOException {
        StringBuilder dialogContext = new StringBuilder();
        if (selectUserInfoCol != null && selectUserInfoCol.size() == 1) {
            dialogContext.append(users.get(selectUserInfoCol.get(0)).getUsername());
            alertView = new AlertView(Alert.AlertType.CONFIRMATION);
            alertView.setTitle("管理员请确认！");
            alertView.setHeaderText("你选择了" + dialogContext + "用户！");
            alertView.setContentText("是否更新？请选择！！！");
            Optional<ButtonType> result = alertView.showAndWait();
            if (result.get() == ButtonType.OK) {
                Integer integer = selectUserInfoCol.get(0);
                System.out.println(integer);
                FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("../view/user.fxml"));
                Parent root = fxmlLoader.load();
                Stage stage = new Stage(StageStyle.DECORATED);
                try {
                    stage.initModality(Modality.WINDOW_MODAL);
                    stage.setScene(new Scene(root));
                    StageDecorate.decorate(stage,root);
                    UserViewController userViewController = fxmlLoader.getController();
                    userInfoHashMap.put("username", users.get(integer).getUsername());
                    userInfoHashMap.put("password", users.get(integer).getPassword());
                    userInfoHashMap.put("nickname", users.get(integer).getNickname());
                    userInfoHashMap.put("isAdmin", users.get(integer).getIsAdmin());
                    userInfoHashMap.put("userRank", users.get(integer).getUserRank());
                    userInfoHashMap.put("userGoal", users.get(integer).getUserGoal());
                    userInfoHashMap.put("userPort", users.get(integer).getUserPort());
                    userInfoHashMap.put("userFriend", users.get(integer).getUserFriend());
                    userViewController.setUserInfoHashMap(userInfoHashMap);
                    stage.setOnShown(new EventHandler<WindowEvent>() {
                        @Override
                        public void handle(WindowEvent event) {
                            userViewController.usernameTextField.setText(userInfoHashMap.get("username").toString());
                            userViewController.usernameTextField.setEditable(false);
                            userViewController.usernameTextField.setDisable(true);
                            if (userInfoHashMap.get("nickname") != null) {
                                userViewController.nicknameTextField.setText(userInfoHashMap.get("nickname").toString());
                            }
                            userViewController.isAdminToggleButton.setSelected(userInfoHashMap.get("isAdmin").equals(1));
                            if (userInfoHashMap.get("userRank") != null) {
                                userViewController.userRankTextField.setText(userInfoHashMap.get("userRank").toString());
                            }
                            userViewController.userGoalTextField.setText(userInfoHashMap.get("userGoal").toString());
                            userViewController.userPortTextField.setText(userInfoHashMap.get("userPort").toString());
                            userViewController.setTreeViewItem(userInfoHashMap.get("userFriend").toString());
                        }
                    });
                    stage.showAndWait();
                    if (userInfoHashMap.get("isChange") != null) {
                        userInfoHashMap = userViewController.getUserInfoHashMap();
                        User user = new User();
                        user.setUsername(userInfoHashMap.get("username").toString());
                        if (userInfoHashMap.get("password").toString().equals("")) {
                            user.setPassword(user.getPassword());
                        } else {
                            String password = userInfoHashMap.get("password").toString();
                            String md5Pwd = MD5Utils.md5(password);
                            user.setPassword(md5Pwd);
                        }
                        user.setNickname(userInfoHashMap.get("nickname").toString());
                        user.setIsAdmin(Integer.parseInt(userInfoHashMap.get("isAdmin").toString()));
                        user.setUserRank(userInfoHashMap.get("userRank").toString());
                        user.setUserGoal(userInfoHashMap.get("userGoal").toString());
                        user.setUserPort(userInfoHashMap.get("userPort").toString());
                        user.setUserFriend(userInfoHashMap.get("userFriend").toString());
                        if (ServiceUtil.serviceUtil.userService.updateUserInfoCol(user) == 1) {
                            insertUserInfoToTable();
                            alertView = new AlertView(Alert.AlertType.INFORMATION);
                            alertView.setTitle("管理员请确认！");
                            alertView.setHeaderText("更新成功！");
                            alertView.setContentText("请查看更新后内容");
                        } else {
                            alertView = new AlertView(Alert.AlertType.ERROR);
                            alertView.setTitle("管理员请确认！");
                            alertView.setHeaderText("数据库错误！");
                            alertView.setContentText("请检查数据库！！！");
                        }
                        alertView.showAndWait();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } else if (selectUserInfoCol == null || selectUserInfoCol.size() == 0) {
            alertView = new AlertView(Alert.AlertType.WARNING);
            alertView.setTitle("管理员请确认！");
            alertView.setHeaderText("你没有选择任何数据项进行修改！");
            alertView.setContentText("请选择一项！！！");
            alertView.showAndWait();
        } else {
            alertView = new AlertView(Alert.AlertType.WARNING);
            alertView.setTitle("管理员请确认！");
            alertView.setHeaderText("你只能选择一项数据进行修改！！！");
            alertView.setContentText("请选择一项！！！");
            alertView.showAndWait();
        }
    }

    public void updateGameLevelCol(ActionEvent event) throws IOException {
        StringBuilder dialogContext = new StringBuilder();
        if (selectGameLevelCol != null && selectGameLevelCol.size() == 1) {
            dialogContext.append(gameLevels.get(selectGameLevelCol.get(0)).getLevel());
            alertView = new AlertView(Alert.AlertType.CONFIRMATION);
            alertView.setTitle("管理员请确认！");
            alertView.setHeaderText("你选择了" + dialogContext + "号难度级别！");
            alertView.setContentText("是否更新？请选择！！！");
            Optional<ButtonType> result = alertView.showAndWait();
            if (result.get() == ButtonType.OK) {
                Integer integer = selectGameLevelCol.get(0);
                System.out.println(integer);
                FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("../view/level.fxml"));
                Parent root = fxmlLoader.load();
                Stage stage = new Stage(StageStyle.DECORATED);
                try {
                    stage.initModality(Modality.WINDOW_MODAL);
                    stage.setScene(new Scene(root));
                    StageDecorate.decorate(stage, root);
                    LevelViewController levelViewController = fxmlLoader.getController();
                    gameLevelHashMap.put("level", gameLevels.get(integer).getLevel());
                    gameLevelHashMap.put("unitSize", gameLevels.get(integer).getUnitSize());
                    gameLevelHashMap.put("sceneWidth", gameLevels.get(integer).getSceneWidth());
                    gameLevelHashMap.put("sceneLength", gameLevels.get(integer).getSceneLength());
                    gameLevelHashMap.put("rowCount", gameLevels.get(integer).getRowCount());
                    gameLevelHashMap.put("colCount", gameLevels.get(integer).getColCount());
                    levelViewController.setNewGameLevelHashMap(gameLevelHashMap);
                    stage.setOnShown(new EventHandler<WindowEvent>() {
                        @Override
                        public void handle(WindowEvent event) {
                            levelViewController.levelTextField.setText(gameLevelHashMap.get("level").toString());

                            levelViewController.levelTextField.setEditable(false);
                            levelViewController.levelTextField.setDisable(true);
                            levelViewController.unitSizeTextField.setText(gameLevelHashMap.get("unitSize").toString());
                            levelViewController.sceneWidthTextField.setText(gameLevelHashMap.get("sceneWidth").toString());
                            levelViewController.sceneLengthTextField.setText(gameLevelHashMap.get("sceneLength").toString());
                            levelViewController.rowCountTextField.setText(gameLevelHashMap.get("rowCount").toString());
                            levelViewController.colCountTextField.setText(gameLevelHashMap.get("colCount").toString());
                        }
                    });
                    stage.showAndWait();
                    if (gameLevelHashMap.get("isChange") != null) {
                        gameLevelHashMap = levelViewController.getNewGameLevelHashMap();
                        GameLevel gameLevel = new GameLevel();
                        gameLevel.setLevel(Integer.parseInt(gameLevelHashMap.get("level").toString()));
                        gameLevel.setUnitSize(Integer.parseInt(gameLevelHashMap.get("unitSize").toString()));
                        gameLevel.setSceneWidth(Integer.parseInt(gameLevelHashMap.get("sceneWidth").toString()));
                        gameLevel.setSceneLength(Integer.parseInt(gameLevelHashMap.get("sceneLength").toString()));
                        gameLevel.setRowCount(Integer.parseInt(gameLevelHashMap.get("rowCount").toString()));
                        gameLevel.setColCount(Integer.parseInt(gameLevelHashMap.get("colCount").toString()));
                        if (ServiceUtil.serviceUtil.gameLevelService.updateGameLevelCol(gameLevel) == 1) {
                            insertGameLevelToTable();
                            alertView = new AlertView(Alert.AlertType.INFORMATION);
                            alertView.setTitle("管理员请确认！");
                            alertView.setHeaderText("更新成功！");
                            alertView.setContentText("请查看更新后内容");
                        } else {
                            alertView = new AlertView(Alert.AlertType.ERROR);
                            alertView.setTitle("管理员请确认！");
                            alertView.setHeaderText("数据库错误！");
                            alertView.setContentText("请检查数据库！！！");
                        }
                        alertView.showAndWait();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } else if (selectGameLevelCol== null || selectGameLevelCol.size() == 0) {
            alertView = new AlertView(Alert.AlertType.WARNING);
            alertView.setTitle("管理员请确认！");
            alertView.setHeaderText("你没有选择任何数据项进行修改！");
            alertView.setContentText("请选择一项！！！");
            alertView.showAndWait();
        } else {
            alertView = new AlertView(Alert.AlertType.WARNING);
            alertView.setTitle("管理员请确认！");
            alertView.setHeaderText("你只能选择一项数据进行修改！！！");
            alertView.setContentText("请选择一项！！！");
            alertView.showAndWait();
        }
    }

    public void updateAvatar(MouseEvent mouseEvent) {
        avatar.setImage(image);
    }
}
